package netty.tcp;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;

import java.nio.charset.Charset;
import java.util.UUID;

/**
 * @ClassName MyServerHandler
 * @Description TODO
 * @Author director吴
 * @Date 2022/4/21 13:22
 * @Version 1.0
 **/
public class MyServerHandler extends SimpleChannelInboundHandler<ByteBuf> {

    private int count;

    @Override
    protected void channelRead0(ChannelHandlerContext ctx, ByteBuf buf) throws Exception {

       byte[] buffer = new byte[buf.readableBytes()];

        buf.readBytes(buffer);

        //将buffer转字符串
        String msg = new String(buffer, Charset.forName("utf-8"));
        System.out.println("服务器接收到消息:"+msg);
        System.out.println("服务器接收的消息量："+(++this.count));


        ByteBuf byteBuf = Unpooled.copiedBuffer("[" + UUID.randomUUID().toString() + "]"+'\n', Charset.forName("utf-8"));

        ctx.writeAndFlush(byteBuf);


    }


    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        cause.printStackTrace();
        ctx.close();
    }
}
